package free.play.service;

import free.play.entity.Hobby;
import free.play.entity.Role;
import free.play.entity.User;
import free.play.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

  @Autowired
  private UserRepository userRepository;

  @Transactional
  public void deleteUser(String loginName) {

    userRepository.deleteByLoginName(loginName);
  }

  @Transactional
  public void addHobbyToUser(String userId, Hobby hobby) {

    User one = userRepository.findOne(userId);
    one.getHobbies().add(hobby);
    userRepository.save(one);
  }

  @Transactional
  public void removeHobbyFromUser(String userId, Hobby hobby) {

    User one = userRepository.findOne(userId);
    one.getHobbies().remove(hobby);
    userRepository.save(one);
  }

  @Transactional
  public void addRoleToUser(String userId, Role role) {

    User one = userRepository.findOne(userId);
    one.getRoles().add(role);
    userRepository.save(one);
  }

  @Transactional
  public void removeRoleFromUser(String userId, Role role) {

    User one = userRepository.findOne(userId);
    one.getRoles().remove(role);
    userRepository.save(one);
  }

  @Transactional
  public User findOneWithRoles(String userId) {

    User one = userRepository.findOne(userId);
    one.getRoles().size();
    return one;
  }

}
